package com.anlu.concurrent.ch4.aqs;

import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/8 13:43
 */
public class TrinityLock {
    //为3，表示允许两个线程同时获得锁
    private final Sync sync = new Sync(3);

    private static final class Sync extends AbstractQueuedSynchronizer {

        Sync(int count) {
            if (count <= 0) {
                throw new IllegalArgumentException("count must large than zero.");
            }
            setState(count);
        }

        @Override
        protected int tryAcquireShared(int reduceCount) {
            for (;;){
                int current = getState();
                int newCount = current - reduceCount;
                if(newCount<0 || compareAndSetState(current,newCount)){
                    return newCount;
                }
            }
        }

        @Override
        protected boolean tryReleaseShared(int returnCount) {
            for(;;){
                int current = getState();
                int newCount =current+ returnCount;
                if(compareAndSetState(current,newCount)){
                    return true;
                }
            }
        }
        final ConditionObject newCondition() {
            return new ConditionObject();
        }
    }

    public void lock(){
        sync.tryAcquireShared(1);
    }
    public void unlock(){
        sync.tryReleaseShared(1);
    }
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean tryLock(){
        return sync.tryAcquireShared(1)>=0;
    }

    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(time));

    }
    public Condition newCondition() {
        return sync.newCondition();
    }


}
